package ynu.edu.controller;

import com.netflix.appinfo.InstanceInfo;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import ynu.edu.entity.Cart;
import ynu.edu.entity.CommonResult;
import ynu.edu.entity.User;
import ynu.edu.feign.ServiceProviderService;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {
    @Resource
    private ServiceProviderService serviceInstance;

    @CircuitBreaker(name="backendB",fallbackMethod = "getCartByIdDown")
    @GetMapping("/getCartById/{userId}")
    @LoadBalanced
//    @Retry(name = "retry1", fallbackMethod = "getCartByIdDown")
    public CommonResult<Cart> getCartById(@PathVariable("userId") Integer userId){
        CommonResult<Cart> result = new CommonResult<>();
        Integer code=200;
        String message = "success";
        Cart cart = new Cart();
        List<String> goods=new ArrayList<>();
        goods.add("电池");
        goods.add("无人机");
        goods.add("笔记本电脑");
        cart.setGoodList(goods);
        User u = serviceInstance.GetUserById(userId);
        cart.setUser(u);
        result.setResult(cart);
        result.setCode(code);
        result.setMsg(message);
        return result;
    }
    public CommonResult<Cart> getCartByIdDown(Integer userId,Exception e){
        e.printStackTrace();
        System.out.println("开始服务降级 B");
        String message="获取用户" + userId + "的信息服务当前出现问题，请稍后再试";
        Integer code=500;
        CommonResult<Cart> result = new CommonResult<>();
        result.setCode(code);
        result.setMsg(message);
        result.setResult(new Cart());
        return result;
    }

}